package com.bear.newsset.adapter;

import android.content.Context;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;

import com.bear.newsset.R;
import com.bear.newsset.entity.NewsDataEntity;
import com.bear.newsset.entity.NewsListEntity;
import com.bear.newsset.holder.NewsOneImgHolder;
import com.bear.newsset.holder.NewsThreeImgHolder;
import com.bear.newsset.holder.NewsZeroImgHolder;
import com.bear.newsset.util.LogUtils;
import com.bear.newsset.util.NewsItemType;
import com.bear.newsset.widget.item.BaseNewsItemView;
import com.bear.newsset.widget.item.NewsItemOneImgView;
import com.bear.newsset.widget.item.NewsItemThreeImgView;
import com.bear.newsset.widget.item.NewsItemZeroImgView;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;

import java.util.List;

/**
 * 新闻列表适配器（RecyclerView）
 */
public class NewsListAdapter extends BaseMultiselectXRecyclerViewAdapter<NewsListEntity> implements
        BaseNewsItemView.OnClickMoreInsideBtnListener, BaseNewsItemView.OnLongClickListener {

    /**
     * 点击更多里边的按钮事件监听器
     */
    public interface OnClickInsideMoreBtnListener {
        void onClick(View v, BaseNewsItemView.CLICK_TYPE type, boolean isSelect,
                     @NonNull NewsListEntity itemData, int position);
    }

    /**
     * 长按弹出更多时的监听器
     */
    public interface OnLongClickMoreListener {
        void onLongClick(BaseNewsItemView v, @NonNull NewsListEntity itemData);
    }

    /**
     * 设置NewsItemView的属性
     */
    public interface OnSetNewsItemView {
        void onSet(BaseNewsItemView view);
    }

    private OnSetNewsItemView mOnSetNewsItemView;
    private OnClickInsideMoreBtnListener mOnClickInsideMoreBtnListener;
    private OnLongClickMoreListener mOnLongClickMoreListener;
    private boolean mEnableLongClickMore = true;

    public NewsListAdapter(@Nullable RequestManager mGlide, @NonNull List<NewsListEntity> list) {
        super( mGlide, list );
    }

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int itemType) {
        return getHolder(viewGroup, itemType);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder viewHolder, int position) {
        super.onBindViewHolder(viewHolder, position);
        NewsDataEntity dataEntity = getDataList().get(position).getItemData();
        String screenName = dataEntity.getAppCode();
        String title = dataEntity.getTitle();


        //删除所有无用的符号
        if( title.contains("&quot;") ) { title = title.replace("&quot;", ""); }

        //如果来源名称不存在
        if( screenName == null || screenName.equals("") ) { screenName = "异世界新闻"; }
        /* Uri图片通过Glide框架进行加载 */
        if(viewHolder instanceof NewsZeroImgHolder) {
            //无图的item
            NewsZeroImgHolder newsZeroImgHolder = (NewsZeroImgHolder) viewHolder;
            //设置新闻标题
            newsZeroImgHolder.getTitle().setText(title);
            //设置来源网站名称
            newsZeroImgHolder.getPosterScreenName().setText(screenName);

        }else if(viewHolder instanceof NewsOneImgHolder) {
            //一张图的item
            NewsOneImgHolder newsOneImgHolder = (NewsOneImgHolder) viewHolder;
            //设置新闻标题
            newsOneImgHolder.getTitle().setText(title);
            if( dataEntity.getImageUrls().size() > 0 ) {
                //加载图片
                getGlide()
                        .load( Uri.parse(dataEntity.getImageUrls().get( 0 )) )
                        .apply( getRequestOptions() )
                        .into( newsOneImgHolder.getImg() );
            }
            //设置来源网站名称
            newsOneImgHolder.getPosterScreenName().setText(screenName);

        }else if(viewHolder instanceof NewsThreeImgHolder) {
            //三张图的item
            NewsThreeImgHolder newsThreeImgHolder = (NewsThreeImgHolder) viewHolder;
            //设置新闻标题
            newsThreeImgHolder.getTitle().setText(title);
            //设置三张图的view
            ImageView[] ivArr = {
                    newsThreeImgHolder.getImg_1(),
                    newsThreeImgHolder.getImg_2(),
                    newsThreeImgHolder.getImg_3()
            };
            List<String> imgs = dataEntity.getImageUrls();
            //加载图片
            for( int i = 0; i < ivArr.length && imgs.size() >= ivArr.length; i++ ) {
                getGlide()
                        .load( Uri.parse( imgs.get( i ) ) )
                        .apply( getRequestOptions() )
                        .into( ivArr[ i ] );
            }
            //设置来源网站名称
            newsThreeImgHolder.getPosterScreenName().setText(screenName);
        }
    }

    /**
     * 获取请求图片的设置
     * @return      {@link RequestOptions}
     */
    private RequestOptions getRequestOptions() {
        return RequestOptions
                .centerCropTransform()
                .placeholder(R.drawable.ic_img_load)    //加载时的图片
                .error(R.drawable.ic_img_error);        //加载错误的图片
    }

    /**
     * 获取item的类型
     * @param position      当前item的下标
     * @return              返回当前item的类型
     */
    @Override
    public int getItemViewType(int position) {
        return getDataList().get(position).getItemType();
    }

    /**
     * 根据type获取holder
     * @param viewGroup     view组
     * @param itemType      当前item的类型，根据类型返回holder
     * @return              返回的holder
     */
    private BaseViewHolder getHolder(ViewGroup viewGroup, int itemType) {
        Context mContext = viewGroup.getContext();
        BaseViewHolder holder;
        BaseNewsItemView view;
        switch( itemType ) {
            case NewsItemType.TYPE_ONE_IMG:         //一张图
                int rand = (int) (Math.random() * 10);
                //大图的权重稍微高一些
                int res = rand > 3 ? R.layout.item_news_1_1_img : R.layout.item_news_1_img;
                view = new NewsItemOneImgView( mContext, res );
                holder = new NewsOneImgHolder( getMultiselectItemView(viewGroup, view) );
                break;
            case NewsItemType.TYPE_THREE_IMG:       //三张图
                view = new NewsItemThreeImgView( mContext );

                holder = new NewsThreeImgHolder( getMultiselectItemView(viewGroup, view) );
                break;
            default:                                //默认无图
                view = new NewsItemZeroImgView( mContext );
                holder = new NewsZeroImgHolder( getMultiselectItemView(viewGroup, view) );
                break;
        }

        //More 上的按钮点击事件监听器
        view.setOnClickMoreInsideBtnListener( this );
        //More 的长按监听器
        view.setOnLongClickListener( this );
        //是否启用长按弹出更多
        view.setEnableLongClickMore( mEnableLongClickMore );
        /* 因为BaseNewsItemView消费了自身的onTouch，然后适配器也通过onTouch实现了点击效果，
           此时适配器的onTouch不会处理，所以需要调用一次按下的效果 */
        setOnItemTouchListener((v, event) -> {
            if( mEnableLongClickMore ) view.onLongClickEvent( event );
            return false;
        });
        //调用者设置ItemView
        if( mOnSetNewsItemView != null ) mOnSetNewsItemView.onSet( view );
        return holder;
    }

    /**
     * 调用该方法后可以继续对ItemView进行设置
     * @param listener      监听器
     */
    public void onSetNewsItemView(OnSetNewsItemView listener) {
        mOnSetNewsItemView = listener;
    }

    private int i = 10000000;
    /**
     * 根据传入的多选View和ItemView创建一个LayoutView返回给Holder
     * @param viewGroup     group
     * @param itemView      item
     * @return              MultiselectItemView
     */
    private View getMultiselectItemView(ViewGroup viewGroup, View itemView) {
        CheckBox muView = new CheckBox( viewGroup.getContext() );

        muView.setId( i++ );
        View v = createMultiselectItemView(viewGroup, itemView, muView, MultiselectGravity.LEFT);

        muView.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setItemMultiselectStatusForMultiselectItemView(v, isChecked);
            }
        });

        setOnCheckedChangeListener(new OnItemCheckedChangeListener() {
            @Override
            public void onChange(View v, boolean isChecked, int position) {
                CheckBox cb = (CheckBox) v;
                LogUtils.e("TAG", "VVV:" + cb.getId());
                cb.setChecked( isChecked );
                cb.setSelected( isChecked );
            }
        });
        return v;
    }

    @Override
    public void onClick(View v, BaseNewsItemView.CLICK_TYPE type, boolean isSelect) {
        if( mOnClickInsideMoreBtnListener != null ) {
            mOnClickInsideMoreBtnListener.onClick(
                    v, type, isSelect, getCurrentItemData(), getCurrentPosition()
            );
        }
    }

    @Override
    public void onLongClick(BaseNewsItemView v) {
        if( mOnLongClickMoreListener != null ) {
            mOnLongClickMoreListener.onLongClick( v, getCurrentItemData() );
        }
    }


    /**
     * More 上的按钮点击事件监听器
     * @param listener      回调
     */
    public void setOnClickInsideMoreBtnListener(OnClickInsideMoreBtnListener listener) {
        mOnClickInsideMoreBtnListener = listener;
    }

    public void setOnLongClickMoreListener(OnLongClickMoreListener listener) {
        mOnLongClickMoreListener = listener;
    }

    /**
     * 设置启用长按弹出更多
     * @param enable    是否启用
     */
    public void setEnableLongClickMore(boolean enable) {
        mEnableLongClickMore = enable;
    }


    @Override
    public int setUpResources() {
        return 0;
    }

    @Override
    public int setDownResources() {
        return 0;
    }
}
